/*
 * Copyright (c) 2018-2999 广州亚米信息科技有限公司 All rights reserved.
 *
 * https://www.gz-yami.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */

package com.yami.shop.api.controller.app;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yami.shop.api.config.DistanceUtils;
import com.yami.shop.bean.app.dto.UnlockRecordDto;
import com.yami.shop.bean.app.param.RechargePackageParam;
import com.yami.shop.bean.model.RechargePackage;
import com.yami.shop.bean.model.UnlockRecord;
import com.yami.shop.bean.model.User;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.dao.UnlockRecordMapper;
import com.yami.shop.dao.UserMapper;
import com.yami.shop.security.util.SecurityUtils;
import com.yami.shop.service.RechargePackageService;
import com.yami.shop.service.UnlockRecordService;
import com.yami.shop.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import ma.glasnost.orika.MapperFacade;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * @author lgh on 2018/10/26.
 */
@RestController
@RequestMapping("/p/unlock")
@Api(tags = "解锁接口")
@Slf4j
public class UnlockController {

    @Autowired
    private UserService userService;
    @Autowired
    private UnlockRecordService unlockRecordService;
    @Autowired
    private UserMapper userMapper;

    /**
     * 解锁用户需要钻石
     */
    private final Integer UNLOCK_USR_DIAMOND_AMOUNT = 990;
    /**
     * 解锁过期时间
     */
    private final Integer UNLOCK_PASS_HOUR = 24;
    @Autowired
    private UnlockRecordMapper unlockRecordMapper;

    @GetMapping
    @ApiOperation(value = "获取解锁记录", notes = "获取解锁记录")
    public ResponseEntity<List<UnlockRecord>> page() {
        String userId = SecurityUtils.getUser().getUserId();
        User user = userService.getById(userId);
        List<UnlockRecord> list = unlockRecordMapper.fandAllNulo(userId);

        for (UnlockRecord unlockRecord : list) {
            User one = userService.getById(unlockRecord.getUnlockedUserId());
            unlockRecord.setUnlockedUserName(one.getNickName());
            unlockRecord.setUnlockedUserPic(one.getPic());
            if (user.getLng() != null && user.getLat() != null && one.getLng() != null && one.getLat() != null) {
                Double dist = DistanceUtils.getDistance(user.getLng(),user.getLat(),one.getLng(),one.getLat());
                unlockRecord.setDistance(dist);
            }

            Integer sta = unlockRecordMapper.unlUser(userId,one.getUserId());
            if(!sta.equals(0)){
                unlockRecord.setUnlStatus(1);
            }else{
                unlockRecord.setUnlStatus(2);
            }
        }
        return ResponseEntity.ok(list);
    }

    @PostMapping("/{id}")
    @ApiOperation(value = "解锁某人", notes = "解锁某人,有vip默认有限用vip名额解锁，再用钻石解锁")
    @Transactional
    public ResponseEntity<String> unlock(@PathVariable("id") @Param(value = "要解锁的用户id") String want2UnlockUserId) {
        String userId = SecurityUtils.getUser().getUserId();
        User fromUser = userService.getById(userId);
        User want2UnlockUser = userService.getById(want2UnlockUserId);
        Date now = new Date();
        Assert.notNull(want2UnlockUser, "解锁对象不存在");

        int count = unlockRecordService.count(Wrappers.lambdaQuery(new UnlockRecord())
                .eq(UnlockRecord::getFromUserId, userId)
                .eq(UnlockRecord::getUnlockedUserId, want2UnlockUserId)
                .eq(UnlockRecord::getStatus, 1));
        if (count > 0) {
            return ResponseEntity.badRequest().body("已解锁过该用户,无法重复解锁");
        }

        UnlockRecord r = new UnlockRecord();
        r.setFromUserId(userId);
        r.setUnlockedUserId(want2UnlockUserId);
        r.setUnlockedUserName(want2UnlockUser.getNickName());
        r.setUnlockedUserPic(want2UnlockUser.getPic());
        r.setPassedTime(DateUtil.offsetHour(now, UNLOCK_PASS_HOUR));
        r.setUnlockType(1);
        r.setUnlockTime(now);
        r.setUnlockPrice(BigDecimal.ZERO);
        r.setStatus(1);


        // TODO: 2021/6/29 添加定时器 使解锁过期
        //使用注册礼解锁
        if(fromUser.getSex().equals("M")){
            if (fromUser.getRegGiftNum() > 0 && now.before(fromUser.getRegGiftEndtime())) {
                //解锁成功直接返回了
                r.setUnlockType(3);
                r.setUnlockPrice(BigDecimal.ZERO);
                unlockRecordService.save(r);
                userMapper.deitGiftNumById(userId);
                return ResponseEntity.ok("已用新用户专属福利解锁");
            }
        }


        //使用邀请礼解锁
        if(fromUser.getInvGiftEndtime() != null){
            if (fromUser.getInvGiftNum() > 0 && now.before(fromUser.getInvGiftEndtime())) {
                //解锁成功直接返回了
                r.setUnlockType(4);
                r.setUnlockPrice(BigDecimal.ZERO);
                unlockRecordService.save(r);
                userMapper.deitInvGiftNumById(userId);
                return ResponseEntity.ok("已用邀请福利解锁");
            }
        }

        //使用邀请人首充礼解锁
        if(fromUser.getInvPleEndtime() != null){
            if (fromUser.getInvPleNum() > 0 && now.before(fromUser.getInvPleEndtime())) {
                //解锁成功直接返回了
                r.setUnlockType(5);
                r.setUnlockPrice(BigDecimal.ZERO);
                unlockRecordService.save(r);
                userMapper.editInvPleNumById(userId);
                return ResponseEntity.ok("已用邀请人首充赠送的礼解锁");
            }
        }


        if (fromUser.getIsVip() == 1) {
            if (fromUser.getTodayUnlockSurplus() > 0) {
                //vip解锁成功直接返回了
                r.setUnlockType(1);
                r.setUnlockPrice(BigDecimal.ZERO);
                unlockRecordService.save(r);
                userMapper.subOneUserUnlockSurplus(userId);
                return ResponseEntity.ok("已用VIP专属解锁福利解锁");
            }

        }
        //都是vip不成功的到这
        if (fromUser.getDiamondNum() >= UNLOCK_USR_DIAMOND_AMOUNT) {
            r.setUnlockType(2);
            r.setUnlockPrice(BigDecimal.valueOf(UNLOCK_USR_DIAMOND_AMOUNT));
            unlockRecordService.save(r);
            userMapper.subOneUserDiamond(userId, UNLOCK_USR_DIAMOND_AMOUNT);
            return ResponseEntity.ok("已消耗" + UNLOCK_USR_DIAMOND_AMOUNT + "钻石解锁");
        }

        return ResponseEntity.ok("VIP空位不足或钻石不足无法解锁，请重试");
    }


}
